﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace WUSTL.SharePoint.WebParts.AnonInfoPath.Layouts.WUSTL.SharePoint.WebParts.AnonInfoPath
{
    public partial class AnonInfoPathConfig : LayoutsPageBase
    {
        public string afvwpSubmitUserKey = SPContext.Current.Site.RootWeb.ID.ToString() + "_SubmitUser";
        public string afvwpSubmitUserValue;

        public void UpdateSettings(object sender, EventArgs e)
        {
            //Grab user from people picker
            if (peUser.ResolvedEntities.Count > 0)
            {
                PickerEntity entity = (PickerEntity)this.peUser.ResolvedEntities[0];
                string userName = entity.Description;

                //Set the value
                afvwpSubmitUserValue = userName;

                //Work with the web
                SPWeb web = SPContext.Current.Site.RootWeb;

                //Check to see if the key exists
                if (web.AllProperties.ContainsKey(afvwpSubmitUserKey))
                {
                    //Ensure value is not null or empty
                    if (!String.IsNullOrEmpty(afvwpSubmitUserValue))
                    {
                        web.AllProperties[afvwpSubmitUserKey] = afvwpSubmitUserValue;
                        web.Update();
                        web.Properties.Update();
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(afvwpSubmitUserValue))
                    {
                        //Key doesn't exist, we need to add it
                        web.AllProperties.Add(afvwpSubmitUserKey, afvwpSubmitUserValue);
                        web.Update();
                        web.Properties.Update();
                    }
                }
            }
            Response.Redirect(litWebURL.Text + "/_layouts/Settings.aspx");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            litWebURL.Text = SPContext.Current.Web.Url;
            if (!Page.IsPostBack)
            {
                //Work with the web
                SPWeb web = SPContext.Current.Site.RootWeb;

                //Check to see if the key exists
                if (web.AllProperties.ContainsKey(afvwpSubmitUserKey))
                {
                    //Ensure value is not null or empty
                    if (!String.IsNullOrEmpty(web.AllProperties[afvwpSubmitUserKey].ToString()))
                    {
                        afvwpSubmitUserValue = web.AllProperties[afvwpSubmitUserKey].ToString();
                        web.Dispose();
                    }
                }

                //Assign the value to the People Editor
                peUser.CommaSeparatedAccounts = @afvwpSubmitUserValue;
                peUser.Validate();
            }
        }
    }
}
